import type { ResponseData, ResponsePaginationData } from '@/utils/request';
import { SUCCESS_CODE } from '@/utils/request';
import type { RequestData } from '@ant-design/pro-table';
import type {
  Tenant,
  TenantAddItem,
  TenantDetailItem,
  TenantEditItem,
  TenantPageQueryListParams,
  TenantTableListItem,
} from './data';
import { request } from 'umi';

export { queryTenantRoleList } from '../TenantRole/service';

/**
 * 获取客户列表
 * @param params
 */
export async function queryTenantList(
  params: TenantPageQueryListParams,
): Promise<RequestData<TenantTableListItem>> {
  const { current: page, pageSize = 20, name } = params;

  const res: ResponsePaginationData<Tenant> = await request('/tenant/list', {
    params: { page, pageSize, name },
  });

  if (res?.code !== SUCCESS_CODE) {
    return { success: false, total: 0, data: [] };
  }

  return {
    success: true,
    total: res.data.total,
    data: res.data.list,
  };
}

export async function queryTenantDetail(params: {
  id: string;
}): Promise<{ success: boolean; data?: TenantDetailItem }> {
  const res = await request(`/tenant/${params.id}`);

  if (res?.code !== SUCCESS_CODE) {
    return { success: false };
  }

  return {
    success: true,
    data: res.data,
  };
}

/**
 * 创建一个客户
 * @param params
 */
export async function addTenant(params: TenantAddItem) {
  const { name, topUserName } = params;

  return request('/tenant/create', {
    method: 'POST',
    data: { name, default_account: topUserName },
  });
}

export async function editTenant(params: TenantEditItem) {
  const { name } = params;

  return request(`/tenant/update`, { method: 'POST', data: { tenantId: params.id, name } });
}

export async function editTenantRoles(params: TenantEditItem) {
  const { id, roles } = params;

  const roleIds = roles?.map((item) => item.id);

  return request(`/tenant/${id}/roles`, { method: 'POST', data: { roleIds } });
}

export async function removeTenant(params: { id: string }): Promise<void> {
  const res: ResponseData<any> = await request(`/tenant/${params.id}`, { method: 'DELETE' });

  if (res.code !== SUCCESS_CODE) {
    throw new Error(res.message);
  }
}
